<?php
// Categories is Menu
function catMenu() {
	global $db, $smarty;
	$Qry = 'SELECT c_name, c_url
			FROM categories
			WHERE c_active = 1
			ORDER BY c_name ASC';
	$result = $db->fetchAll($Qry);

	$smarty->assign('catMenuTop', $result);
}

// Clear special character
function cleaner($str, $encode_ent = false) {
	$str = trim($str);

	if ($encode_ent) {
// 		$str = str_replace("'", '’', $str);
		$str = str_replace("'", '&#39;', $str);
// 		$str = htmlentities($str);
	}

	return $str;
}
/**
 * Upload images
 */
function xupload($xfile, $path, $name) {
	$max_size = '200000';

	if (is_uploaded_file($xfile['tmp_name'])){
		if ($xfile['size'] > $max_size)
			$nd['error'] = 'File size too big than ' . round($max_size/1000) . 'KB.';
		else{
			$ftype = false;

			if (($xfile["type"] == "image/gif") || ($xfile["type"] == "image/jpeg") || ($xfile["type"] == "image/png") || ($xfile["type"] == "image/pjpeg"))
				$ftype = true;

			if (fileext($xfile['name']) == true && $ftype == true){
				$fn = $xfile['name'];

				if ($name != '')
					$fn = $name;

				$filez = $path . filename($fn);
				$res = copy($xfile['tmp_name'], $filez);

				if (!$res)
					$nd['error'] = 'Unable to upload photos, please CHMOD folder ' . $path . ' to 755 or 777.';
				else{
					$nd['filename'] = filename($fn);
					$nd['error'] = '';
				}
			}else
				$nd['error'] = 'Amiss format Image.';

		}
	}
	return $nd;
}

function fileext($filename) {
	$fext = false;
	$extension = strtoupper(substr($filename, strlen($filename) - 4, 4));
	switch (strtoupper($extension)){
		case '.GIF':
		case '.PNG':
		case '.JPG':
			$fext = true;
		break;
		default:
		break;
	}
	return $fext;
}

function filename($nm) {
	$nd = str_replace(chr(32), '-', $nm);
	$nd = strtolower($nd);
	return $nd;
}

/**
 * Remove \n\r
 */
function removeNewLine($value) {
	$string = preg_replace('@[\s]{2,}@', ' ', $value);
	return trim(str_replace(array(
			"/\n|\r/",
			"\""
	), array(
			"",
			"'"
	), $string));
}

/**
 * Remove unicode
 * @return string
 */
function remove_unicode($str, $lower = false, $strip_tags = false){
	if ($str == '')
		return false;

	$char = array('-–-', '---', '--');
	$str = trim($str);
	if ($strip_tags) {
		$chars = array(
				'a'=>array(
						'ấ',
						'ầ',
						'ẩ',
						'ẫ',
						'ậ',
						'Ấ',
						'Ầ',
						'Ẩ',
						'Ẫ',
						'Ậ',
						'ắ',
						'ằ',
						'ẳ',
						'ẵ',
						'ặ',
						'Ắ',
						'Ằ',
						'Ẳ',
						'Ẵ',
						'Ặ',
						'á',
						'à',
						'ả',
						'ã',
						'ạ',
						'â',
						'ă',
						'Á',
						'À',
						'Ả',
						'Ã',
						'Ạ',
						'Â',
						'Ă'
				),
				'e'=>array(
						'ế',
						'ề',
						'ể',
						'ễ',
						'ệ',
						'Ế',
						'Ề',
						'Ể',
						'Ễ',
						'Ệ',
						'é',
						'è',
						'ẻ',
						'ẽ',
						'ẹ',
						'ê',
						'É',
						'È',
						'Ẻ',
						'Ẽ',
						'Ẹ',
						'Ê'
				),
				'i'=>array(
						'í',
						'ì',
						'ỉ',
						'ĩ',
						'ị',
						'Í',
						'Ì',
						'Ỉ',
						'Ĩ',
						'Ị',
						'î'
				),
				'o'=>array(
						'ố',
						'ồ',
						'ổ',
						'ỗ',
						'ộ',
						'Ố',
						'Ồ',
						'Ổ',
						'Ô',
						'Ộ',
						'ớ',
						'ờ',
						'ở',
						'ỡ',
						'ợ',
						'Ớ',
						'Ờ',
						'Ở',
						'Ỡ',
						'Ợ',
						'ó',
						'ò',
						'ỏ',
						'õ',
						'ọ',
						'ô',
						'ơ',
						'Ó',
						'Ò',
						'Ỏ',
						'Õ',
						'Ọ',
						'Ô',
						'Ơ'
				),
				'u'=>array(
						'ứ',
						'ừ',
						'ử',
						'ữ',
						'ự',
						'Ứ',
						'Ừ',
						'Ử',
						'Ữ',
						'Ự',
						'ú',
						'ù',
						'ủ',
						'ũ',
						'ụ',
						'ư',
						'Ú',
						'Ù',
						'Ủ',
						'Ũ',
						'Ụ',
						'Ư'
				),
				'y'=>array(
						'ý',
						'ỳ',
						'ỷ',
						'ỹ',
						'ỵ',
						'Ý',
						'Ỳ',
						'Ỷ',
						'Ỹ',
						'Ỵ'
				),
				'd'=>array(
						'đ',
						'Đ'
				)
		);
	} else {
		$chars = array(
				'a'=>array(
						'ấ',
						'ầ',
						'ẩ',
						'ẫ',
						'ậ',
						'Ấ',
						'Ầ',
						'Ẩ',
						'Ẫ',
						'Ậ',
						'ắ',
						'ằ',
						'ẳ',
						'ẵ',
						'ặ',
						'Ắ',
						'Ằ',
						'Ẳ',
						'Ẵ',
						'Ặ',
						'á',
						'à',
						'ả',
						'ã',
						'ạ',
						'â',
						'ă',
						'Á',
						'À',
						'Ả',
						'Ã',
						'Ạ',
						'Â',
						'Ă'
				),
				'e'=>array(
						'ế',
						'ề',
						'ể',
						'ễ',
						'ệ',
						'Ế',
						'Ề',
						'Ể',
						'Ễ',
						'Ệ',
						'é',
						'è',
						'ẻ',
						'ẽ',
						'ẹ',
						'ê',
						'É',
						'È',
						'Ẻ',
						'Ẽ',
						'Ẹ',
						'Ê'
				),
				'i'=>array(
						'í',
						'ì',
						'ỉ',
						'ĩ',
						'ị',
						'Í',
						'Ì',
						'Ỉ',
						'Ĩ',
						'Ị',
						'î'
				),
				'o'=>array(
						'ố',
						'ồ',
						'ổ',
						'ỗ',
						'ộ',
						'Ố',
						'Ồ',
						'Ổ',
						'Ô',
						'Ộ',
						'ớ',
						'ờ',
						'ở',
						'ỡ',
						'ợ',
						'Ớ',
						'Ờ',
						'Ở',
						'Ỡ',
						'Ợ',
						'ó',
						'ò',
						'ỏ',
						'õ',
						'ọ',
						'ô',
						'ơ',
						'Ó',
						'Ò',
						'Ỏ',
						'Õ',
						'Ọ',
						'Ô',
						'Ơ'
				),
				'u'=>array(
						'ứ',
						'ừ',
						'ử',
						'ữ',
						'ự',
						'Ứ',
						'Ừ',
						'Ử',
						'Ữ',
						'Ự',
						'ú',
						'ù',
						'ủ',
						'ũ',
						'ụ',
						'ư',
						'Ú',
						'Ù',
						'Ủ',
						'Ũ',
						'Ụ',
						'Ư'
				),
				'y'=>array(
						'ý',
						'ỳ',
						'ỷ',
						'ỹ',
						'ỵ',
						'Ý',
						'Ỳ',
						'Ỷ',
						'Ỹ',
						'Ỵ'
				),
				'd'=>array(
						'đ',
						'Đ'
				),
				''=>array(
						'/',
						'\\',
						',',
						'.',
						'"',
						'\"',
						"&quot;",
						'*',
						'{',
						'}',
						'<',
						'>',
						'(',
						')',
						'&lt;',
						'&gt;',
						'?',
						"'",
						"\'",
						'~',
						'#',
						'^',
						'“',
						'”',
						':',
						';',
						'&',
						'&amp;',
						'+',
						'=',
						'%',
						'$',
						'@',
						'!',
						"'"
				),
				'pc'=>array(
						'%'
				),
				'-'=>array(
						' ',
						'%20',
						'_'
				)
		);
	}

	foreach ($chars as $key=>$arr){
		foreach ($arr as $val){
			$str = str_replace($val, $key, $str);
		}
	}

	$str = str_replace($char, '-', $str);

	if ($lower)
		$str = strtolower($str);

	return $str;
}

/**
 * Truncate string
 *
 * @param string $str
 * @param int $len
 * @param string $charset
 * @return string
 */
function truncate($str, $len, $charset = 'UTF-8') {
	$str = strip_tags($str);
	$str = htmlspecialchars($str);
	$str = html_entity_decode($str, ENT_QUOTES, $charset);

	if (mb_strlen($str, $charset) > $len){
		$arr = explode(' ', $str);
		$str = mb_substr($str, 0, $len, $charset);
		$arrRes = explode(' ', $str);
		$last = $arr[count($arrRes) - 1];
		unset($arr);
		if (strcasecmp($arrRes[count($arrRes) - 1], $last)){
			unset($arrRes[count($arrRes) - 1]);
		}
		return implode(' ', $arrRes);
	// 		return implode(' ', $arrRes) . ' ...';
	}
	return $str;
}

/**
 * Administrator
 * Panigation
 */
function ad_panigation($num, $perpage, $curPage, $url = '', $page = 10, $type = false) {
	global $lang;

	$sth = '<ul class="pagination pagination-sm">';

	if ($num > $perpage){

		if ($type)
			$query = '&amp;p=';
		else
			$query = '?p=';

		$lastPage = ceil($num / $perpage);

		$from = $curPage - $page;
		if ($from <= 0)
			$from = 1;

		$to = $curPage + $page;
		if ($to > $lastPage)
			$to = $lastPage;

			// The first page
		$sth .= '<li><a href="' . $url . '"><i class="icon-small icon-fast-backward"></i></a></li>';
		// Prev page
		if ($curPage > 1){
			$sth .= '<li><a href="' . $url . $query . ($curPage - 1) . '"><i class="icon-small icon-step-backward"></i></a></li>';
		}

		for ($i = $from; $i <= $to; $i++){
			if ($curPage == $i)
				$sth .= '<li class="active"><a><span class="sr-only">' . $i . '</span></a></li>';
			else
				$sth .= '<li><a href="' . $url . $query . $i . '">' . $i . '</a></li>';
		}

		// Next page
		if ($lastPage > $curPage){
			$sth .= '<li><a href="' . $url . $query . ($curPage + 1) . '"><i class="icon-small icon-step-forward"></i></a></li>';
		}
		// The last page
		$sth .= '<li><a href="' . $url . $query . $lastPage . '"><i class="icon-small icon-fast-forward"></i></a></li>';
	}

	$sth .= '</ul>';

	return $sth;
}

function panigation($num, $perpage, $curPage, $url = '', $page = 10, $type = false) {
	global $lang;

	$sth = '';

	if ($num > $perpage){

		if ($type)
			$query = '/';
		else
			$query = '?p=';

		$lastPage = ceil($num / $perpage);

		$from = $curPage - $page;
		if ($from <= 0)
			$from = 1;

		$to = $curPage + $page;
		if ($to > $lastPage)
			$to = $lastPage;

		// The first page
		$sth .= '<li class="navpage"><a href="' . $url . '">First</a></li>';
		// Prev page
		if ($curPage > 1){
			if ($curPage == 2)
				$sth .= '<li class="navpage"><a href="' . $url . '"><</a></li>';
			else
				$sth .= '<li class="navpage"><a href="' . $url . $query . ($curPage - 1) . '"><</a></li>';
		}

		for ($i = $from; $i <= $to; $i++){
			if ($curPage == $i)
				$sth .= '<li class="current">' . $i . '</li>';
			else {
				if ($i == 1)
					$sth .= '<li><a href="' . $url . '">' . $i . '</a></li>';
				else
					$sth .= '<li><a href="' . $url . $query . $i . '">' . $i . '</a></li>';
			}
		}

		// Next page
		if ($lastPage > $curPage){
			$sth .= '<li class="navpage"><a href="' . $url . $query . ($curPage + 1) . '">></a></li>';
		}
		// The last page
		$sth .= '<li class="navpage"><a href="' . $url . $query . $lastPage . '">Last</a></li>';
	}

	return $sth;
}

/**
 * **************************************************
 * Remember that header() must be called before any actual output is sent,
 * either by normal HTML tags, blank lines in a file, or from PHP.
 * ***************************************************
 */
function movePage($num, $url) {
	static $http = array(
			100=>"HTTP/1.1 100 Continue",
			101=>"HTTP/1.1 101 Switching Protocols",
			200=>"HTTP/1.1 200 OK",
			201=>"HTTP/1.1 201 Created",
			202=>"HTTP/1.1 202 Accepted",
			203=>"HTTP/1.1 203 Non-Authoritative Information",
			204=>"HTTP/1.1 204 No Content",
			205=>"HTTP/1.1 205 Reset Content",
			206=>"HTTP/1.1 206 Partial Content",
			300=>"HTTP/1.1 300 Multiple Choices",
			301=>"HTTP/1.1 301 Moved Permanently",
			302=>"HTTP/1.1 302 Found",
			303=>"HTTP/1.1 303 See Other",
			304=>"HTTP/1.1 304 Not Modified",
			305=>"HTTP/1.1 305 Use Proxy",
			307=>"HTTP/1.1 307 Temporary Redirect",
			400=>"HTTP/1.1 400 Bad Request",
			401=>"HTTP/1.1 401 Unauthorized",
			402=>"HTTP/1.1 402 Payment Required",
			403=>"HTTP/1.1 403 Forbidden",
			404=>"HTTP/1.1 404 Not Found",
			405=>"HTTP/1.1 405 Method Not Allowed",
			406=>"HTTP/1.1 406 Not Acceptable",
			407=>"HTTP/1.1 407 Proxy Authentication Required",
			408=>"HTTP/1.1 408 Request Time-out",
			409=>"HTTP/1.1 409 Conflict",
			410=>"HTTP/1.1 410 Gone",
			411=>"HTTP/1.1 411 Length Required",
			412=>"HTTP/1.1 412 Precondition Failed",
			413=>"HTTP/1.1 413 Request Entity Too Large",
			414=>"HTTP/1.1 414 Request-URI Too Large",
			415=>"HTTP/1.1 415 Unsupported Media Type",
			416=>"HTTP/1.1 416 Requested range not satisfiable",
			417=>"HTTP/1.1 417 Expectation Failed",
			500=>"HTTP/1.1 500 Internal Server Error",
			501=>"HTTP/1.1 501 Not Implemented",
			502=>"HTTP/1.1 502 Bad Gateway",
			503=>"HTTP/1.1 503 Service Unavailable",
			504=>"HTTP/1.1 504 Gateway Time-out"
	);
	header($http[$num]);
	header("Location: $url");
	exit();
}

function auto_links($content) {
	if (!$content)
		return false;

		// words
	$words = parse_words($content);

	// Get tags file
	$file = $_SERVER['DOCUMENT_ROOT'] . '/' . 'tag.txt';
	if (file_exists($file))
		$str = file_get_contents($file);

	if ($str){
		$tags = explode("\n", $str);

		foreach ($tags as $line){
			$line = trim($line);
			$lastDelimiterPos = strrpos($line, ',');
			$url = substr($line, $lastDelimiterPos + 1);
			$keywords = substr($line, 0, $lastDelimiterPos);

			if (!empty($keywords) && !empty($url))
				$kw_array[$keywords] = $url;
		}

		foreach ($kw_array as $name=>$url){
			$name = preg_quote($name, '/');

			$newArray[] = $name;
		}

		// Compare 2 arrays
		$result = array_intersect($newArray, $words);
		usort($result, 'mysort');

		$newTags = array();
		foreach ($kw_array as $name=>$url){
			if (in_array($name, $result)){
				$name = preg_quote($name, '/');
				$replace = '<a href="' . $url . '" title="' . $name . ' game" target="_blank">' . $name . '</a>';

				$newTags[$name] = $replace;
			}
		}

		return strReplaceAssoc($newTags, $content);
	}
}

function strReplaceAssoc(array $replace, $subject) {
	return str_replace(array_keys($replace), array_values($replace), $subject);
}

function mysort($a, $b) {
	return strlen($b) - strlen($a);
}

function clean($string) {
	$string = strip_tags($string);
	$string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
	$string = preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
	$string = trim($string);
	$string = ltrim($string, '-');
	$string = rtrim($string, '-');

	return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}

function parse_words($contents) {
	$contents = clean($contents);
	$x = explode("-", $contents);
	$y = array();

	// Word
	foreach ($x as $key=>$val){
		$y[] = trim($val);
	}

	// 2 Words
	for ($i = 0; $i < count($x) - 1; $i++){
		$y[] = trim($x[$i]) . " " . trim($x[$i + 1]);
	}

	// 3 Words
	for ($i = 0; $i < count($x) - 2; $i++){
		$y[] = trim($x[$i]) . " " . trim($x[$i + 1]) . " " . trim($x[$i + 2]);
	}

	return $y;
}

function getPost($id = null) {
	global $db;

	if ($id) {
		$sql = "SELECT up, down
				FROM games
				WHERE g_id = $id";
		$statement = $db->fetchAll($sql);

		return $statement;
	}
}

function buttonSet($id = null) {
	if ($id) {
		$post = getPost($id);
		$found = getByUser($id);

		if (!empty($found)) {
			$out  = '<div class="rateWrapper">';
			$out .= '<span class="rateDone rateUp';
			$out .= $found[0]['rate'] == 1 ? ' active' : null;
			$out .= '" data-item="';
			$out .= $id;
			$out .= '"><span class="rateUpN">';
			$out .= intval($post[0]['up']);
			$out .= '</span></span>';
			$out .= '<span class="rateDone rateDown';
			$out .= $found[0]['rate'] == 0 ? ' active' : null;
			$out .= '" data-item="';
			$out .= $id;
			$out .= '"><span class="rateDownN">';
			$out .= intval($post[0]['down']);
			$out .= '</span></span>';
			$out .= '</div>';
		} else {
			$out  = '<div class="rateWrapper">';
			$out .= '<span class="rate rateUp" data-item="';
			$out .= $id;
			$out .= '"><span class="rateUpN">';
			$out .= intval($post[0]['up']);
			$out .= '</span></span>';
			$out .= '<span class="rate rateDown" data-item="';
			$out .= $id;
			$out .= '"><span class="rateDownN">';
			$out .= intval($post[0]['down']);
			$out .= '</span></span>';
			$out .= '</div>';
		}

		return $out;
	}
}

function getByUser($id = null) {
	global $db;

	if ($id) {
		$user = getenv('REMOTE_ADDR');

		$sql = "SELECT rate
				FROM ratings
				WHERE user = '$user' AND item = $id";
		$statement = $db->fetchAll($sql);

		return $statement;
	}
}

function isSubmitted($id = null) {
	if ($id) {
		$found = getByUser($id);
		return !empty($found) ? true : false;
	}
	return true;
}

function addRating($id = null, $rate = null) {
	if ($id) {
		global $db;

		$rate = $rate == 1 ? 1 : 0;
		$user = getenv('REMOTE_ADDR');

		$sql = "INSERT INTO ratings (user, item, rate) VALUES ('$user', $id, $rate)";
		$statement = $db->Query($sql);

		if ($statement)
			return updateRating($id, $rate);
		else
			return false;
	}
	return false;
}

function updateRating($id = null, $rate = null) {
	if ($id) {
		global $db;

		$sql  = "UPDATE games SET ";
		$sql .= $rate == 1 ? " up = up + 1 " : " down = down + 1 ";
		$sql .= "WHERE g_id = $id";

		$statement = $db->Query($sql);
		return $statement;
	}
}

// add game played
function gamePlayed($id = null) {
	if ($id) {
		$found = getUserPlay($id);

		if (!$found) {
			addPlayed($id);
		}
	}
}

function getUserPlay($id = null) {
	global $db;

	if ($id) {
		$user = getenv('REMOTE_ADDR');
		$getNow = new DateTime('now');
		$now = $getNow->format('Y-m-d');

		$sql = "SELECT gid
				FROM played
				WHERE user = '$user' AND gid = $id AND updated = '" . $now . "'";
		$statement = $db->numRows($sql);

		return $statement;
	}
}

function addPlayed($id = null) {
	if ($id) {
		global $db;

		$user = getenv('REMOTE_ADDR');
		$getNow = new DateTime('now');
		$now = $getNow->format('Y-m-d');

		$sql = "INSERT INTO played (user, gid, updated) VALUES ('$user', $id, '$now')";
		$statement = $db->Query($sql);

		if ($statement)
			return updatePlayed($id);
		else
			return false;
	}
	return false;
}

function updatePlayed($id = null) {
	if ($id) {
		global $db;

		$sql = "UPDATE games SET views = views + 1 WHERE g_id = $id";

		$statement = $db->Query($sql);
		return $statement;
	}
}








